package main

import (
	"github.com/gin-gonic/gin"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/your_username/backend-login-system/controllers"
	"github.com/your_username/backend-login-system/middleware"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
)

var globalDB *gorm.DB

func main() {
	var err error
	// 配置数据库连接，这里使用MySQL示例，根据实际情况修改
	dsn := "user:password@tcp(127.0.0.1:3306)/your_database_name?charset=utf8mb4&parseTime=True&loc=Local"
	globalDB, err = gorm.Open("mysql", dsn, &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}

	// 自动迁移用户模型结构（如果表不存在则创建）
	globalDB.AutoMigrate(&models.User{})

	r := gin.Default()

	// 注册路由
	api := r.Group("/api")
	{
		auth := api.Group("/auth")
		{
			auth.POST("/login", controllers.Login)
			auth.POST("/register", controllers.Register)
		}
		protected := api.Group("/protected")
		{
			protected.Use(middleware.AuthMiddleware())
			protected.GET("/data", controllers.GetProtectedData)
		}
	}

	// 启动服务，监听端口，可根据实际情况修改
	if err := r.Run(":8888"); err != nil {
		log.Fatal("服务启动失败:", err)
	}
}
